package com.scheduler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.common.utils.HttpUtil;
import com.entity.GateTrend;
import com.entity.Marketlist;
import com.entity.Tickers;
import com.service.GateTrendService;
import com.service.MarketlistService;
import com.service.TickersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Configurable
@EnableScheduling
public class GateScheduler {


    @Autowired
    private TickersService tickersService;

    @Autowired
    private GateTrendService gateTrendService;

    @Autowired
    private MarketlistService marketlistService;


    private Map<String,Tickers> startMap=new HashMap<>();
    private Map<String,Tickers> endMap=new HashMap<>();

    private Map<String,BigDecimal> hMap=new HashMap<>();

    private  Map<String,String> hcode=new HashMap<>();

    private  static  boolean flag=true;
    private Long sysStartTime;
    private Long sysEndTime;
    /**
     * 新高数据
     */
    @Scheduled(cron = "0 55 22 17 * *")
    public void getHigh(){
        Wrapper<Marketlist> wr=new EntityWrapper<>();
        List<Marketlist> marketlists = marketlistService.selectList(wr);
        if(!CollectionUtils.isEmpty(marketlists)){

            for (Marketlist marketlist : marketlists) {
                List<Double> doubles=new ArrayList<>();
                String pair = marketlist.getPair();
                if(pair.contains("_usdt")){
                    String url="https://www.gateio.ch/json_svr/query/?u=10&c=8930156&type=tvkline&symbol="+pair+"&from=1590155919&to=1621259979&interval=2592000";
                    String str = HttpUtil.sendGet(url, null);

                    String s1 = str.replaceAll("date,open,high,low,close,volume", "");
                    String[] split = s1.split("00000,");
                    for (String s2 : split) {
                        String[] split1 = s2.split(",");
                        if(!(split1.length<2)){
                            doubles.add(new Double(split1[1]));
                        }
                    }
                    if(!CollectionUtils.isEmpty(doubles)){
                        double asDouble = doubles.stream().mapToDouble(Double::doubleValue).max().getAsDouble();
                        System.out.println(pair+"==h==="+asDouble);
                        marketlist.setHighPriceAll(asDouble+"");
                        marketlistService.updateById(marketlist);
                    }
                }
            }
        }

          }
    /**
     * x分钟获取一次全盘数据
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void getData(){

        if(flag){
            Wrapper<Marketlist> wr=new EntityWrapper<>();
            List<Marketlist> marketlists = marketlistService.selectList(wr);
            if(!CollectionUtils.isEmpty(marketlists)){
                for (Marketlist marketlist : marketlists) {
                    if(!StringUtils.isEmpty(marketlist.getHighPriceAll())){
                        if(!marketlist.getHighPriceAll().contains("E")){
                            String pair = marketlist.getPair();
                            String highPriceAll = marketlist.getHighPriceAll();
                            hMap.put(pair,new BigDecimal(highPriceAll));
                        }
                    }
                }
            }
            flag=false;
        }


        endMap=new HashMap<>();
        List<Tickers> list=new ArrayList<>();
        String result = HttpUtil.sendGet("https://data.gateapi.io/api2/1/tickers", null);
        sysEndTime = System.currentTimeMillis() / 1000;
        if(null!=sysStartTime&&null!=sysEndTime){
            long intervalTime = sysEndTime - sysStartTime;
//            System.out.println("时间差"+intervalTime);

            if(intervalTime>70){
                startMap.clear();//数据出错，清空数据
            }
        }


        Map maps = (Map) JSON.parse(result);
        for (Object map : maps.entrySet()){
           // System.out.println(((Map.Entry)map).getKey()+"" + ((Map.Entry)map).getValue());
            Tickers tickers = JSONObject.parseObject(((Map.Entry) map).getValue() + "", Tickers.class);
            list.add(tickers);
            endMap.put(((Map.Entry)map).getKey()+"",tickers);//.getLast()
        }

        List<GateTrend> gateTrends=new ArrayList<>();
        //对比
        for (Map.Entry<String, Tickers> en : endMap.entrySet()) {

            String endTrend= "";
            String startTrend = "";

            Tickers endtickers = endMap.get(en.getKey());
            if(null!=endtickers){
                endTrend= endMap.get(en.getKey()).getLast()+"";
            }

            BigDecimal bigDecimal = hMap.get(en.getKey());
            if(null!=bigDecimal){
                if(new BigDecimal(endTrend).compareTo(bigDecimal)==1){
                    String s = hcode.get(en.getKey());
                    if(StringUtils.isEmpty(s)){
                        System.out.println("历史新高"+en.getKey());
                        hcode.put(en.getKey(),endTrend);
                        try {
                            this.playmp3();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            Tickers starttickers = startMap.get(en.getKey());
            if(null!=starttickers){
                startTrend = startMap.get(en.getKey()).getLast()+"";
            }

            String percentChange = endMap.get(en.getKey()).getPercentChange();
            if(!StringUtils.isEmpty(endTrend)&&!StringUtils.isEmpty(startTrend)){


                if((new BigDecimal(endTrend).compareTo(new BigDecimal("0.001"))==1)
                &&(new BigDecimal(startTrend).compareTo(new BigDecimal("0.001"))==1)){

                BigDecimal trend=new BigDecimal(endTrend).subtract(new BigDecimal(startTrend));
                BigDecimal zf = trend.divide(new BigDecimal(startTrend),4, BigDecimal.ROUND_HALF_UP);

                if(zf.compareTo(new BigDecimal("0.15"))==1){
                    //出现大于15涨幅的 ,jilu key
                    BigDecimal hbg = hMap.get(en.getKey());

                    if(null==hbg){
                        System.out.println(en.getKey()+"====代码==="+"，一分钟涨幅="+zf+",当前价格="+endTrend+",前1分钟价格="+startTrend+",当前涨幅="+endtickers.getPercentChange());//当前价格，之前价格
                    }else{
                        System.out.println(en.getKey()+"====代码==="+"，一分钟涨幅="+zf+",当前价格="+endTrend+",前1分钟价格="+startTrend+",当前涨幅="+endtickers.getPercentChange()+"历史最高点=="+hbg);//当前价格，之前价格
                    }
                   GateTrend gateTrend=new GateTrend();
                    gateTrend.setName(en.getKey());
                    gateTrend.setStartPrice(new BigDecimal(startTrend));
                    gateTrend.setEndPrice(new BigDecimal(endTrend));
                    gateTrend.setStatus(2);
                    gateTrend.setTime(System.currentTimeMillis()/1000);
                    gateTrend.setZf(zf);
                    gateTrend.setTrend(percentChange);//当前涨幅
                    gateTrends.add(gateTrend);
                    try {
                        this.playmp3();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else{
//                    System.out.print(en.getKey()+"-");

                    GateTrend gateTrend=new GateTrend();
                    gateTrend.setName(en.getKey());
                    gateTrend.setStartPrice(new BigDecimal(startTrend));
                    gateTrend.setEndPrice(new BigDecimal(endTrend));
                    gateTrend.setStatus(1);
                    gateTrend.setTime(System.currentTimeMillis()/1000);
                    gateTrend.setZf(zf);
                    gateTrend.setTrend(percentChange);//当前涨幅
                    gateTrends.add(gateTrend);
                }

                }
            }
        }
        System.out.println("");

        if(!CollectionUtils.isEmpty(gateTrends)){
            gateTrendService.insertBatch(gateTrends);
        }

        startMap=endMap;
        sysStartTime=sysEndTime;
//        tickersService.insertBatch(list);
    }


    public void playmp3() throws IOException {
        File file = new File("D:\\yijie.wav");
        URL url =  file.toURI().toURL();
        InputStream inputStream = url.openStream(); // 获得音乐文件的输入流
        AudioStream audioStream =new AudioStream(inputStream);
        AudioPlayer.player.start(audioStream);
    }

}
